//
//  SHHLoginVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/5.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

@objc protocol SHHLoginVCDelegate {
    func changeState()
}

class SHHLoginVC: UIViewController {

    
    @IBOutlet weak var userTextField: UITextField!
    
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var backImageView: UIImageView!
    
    //申明闭包属性，用来进行传值，登录的时候将用户名显示在button上
    var myBlock:((_ :String)->Void)?
    
    //申明代理
    var delegate:SHHLoginVCDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "登录"
        
        //背景图模糊效果
        let fixView = FXBlurView(frame: UIScreen.mainScreen().bounds)
        fixView.dynamic = false
        fixView.blurRadius = 15
        fixView.tintColor = UIColor.clearColor()
        self.backImageView.addSubview(fixView)
        
        //导航栏左按钮（返回）
        var normalImg = UIImage(named: "iconfont-iconfanhui-2")
        normalImg = normalImg?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: normalImg, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("leftAction:"))
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //返回按钮的点击事件
    func leftAction(sender:UIBarButtonItem) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    
    //登录按钮的点击事件
    @IBAction func LoginAction(sender: AnyObject) {
        
        let alertController = UIAlertController(title: "温馨提示", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        if self.userTextField.text == "" || self.passwordTextField.text == "" {
            alertController.message = "不能为空"
            alertController.addAction(defaultAction)
            alertController.addAction(cancelAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }else{
            
            AVUser.logInWithUsernameInBackground(self.userTextField.text, password: self.passwordTextField.text, block: { (user:AVUser!, error:NSError!) -> Void in
//                print(user.username)
                print("走了吗")
                if user != nil {
                    print("我日了就")
                    let alert = UIAlertController(title: "温馨提示", message: "登录成功", preferredStyle: UIAlertControllerStyle.Alert)
                    
                    let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction) -> Void in
                        self.delegate?.changeState()
                        //调用闭包
                        let query = AVQuery(className: "UserInfo")
                        query.whereKey("user_id", equalTo: user["user_id"])
                        let userArray = query.findObjects()
                        if userArray.isEmpty || userArray == nil {
                            self.myBlock!(user.username)
                        }else{
                            let resultUser = userArray.first
                            self.myBlock!((resultUser!["name"] as! String))
                        }
                        
                        
                        //点击确认跳转页面
                        self.dismissViewControllerAnimated(true, completion: nil)
                    })
                    
                    let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
                    alert.addAction(defaultAction)
                    alert.addAction(cancelAction)
                    self.presentViewController(alert, animated: true, completion: nil)
                    
                }else{
                    let alert = UIAlertController(title: "温馨提示", message: "登录失败", preferredStyle: UIAlertControllerStyle.Alert)
                    let defaultAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                    
                    alert.addAction(defaultAction)
                    
                    self.presentViewController(alert, animated: true, completion: nil)
                }
                
            })
            
        }
    }
    
    
    //注册按钮的点击事件
    @IBAction func RegisterAction(sender: AnyObject) {
        
        let registerVC = SHHRegisterVC()
        self.navigationController?.pushViewController(registerVC, animated: true)
    }
    
    //点击空白处，键盘回收
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
